<?php

class Chat
{
    protected static $_dbh;
    
    protected $_user;
    
    public function __construct(User_Abstract $user)
    {
        self::$_dbh = Framework_Registry::get('dbh');
        $this->_user = $user;
    }
    
    public function addMessage($user_id, $message)
    {
        return empty($message) ? null : self::$_dbh
            ->query("INSERT INTO tetatet
                     SET tetatet_user_id_from=?,
                         tetatet_user_id_to=?,
                         tetatet_message=?",
                     $this->_user->getUserId(),
                     $user_id,
                     $message);
    }
    
    public function getMessages($user_id, $sum = 10, $page = 0, &$paging = 0)
    {
        $result = self::$_dbh->selectPage($total_rows,
                                   'SELECT * FROM tetatet
                                    WHERE (tetatet_user_id_from=? AND tetatet_user_id_to=?)
                                        OR (tetatet_user_id_from=? AND tetatet_user_id_to=?)
                                    ORDER BY tetatet_id DESC LIMIT ?d, ?d',
                                    $this->_user->getUserId(), $user_id, $user_id, $this->_user->getUserId(),
                                    $page*$sum, $sum);
        $paging = paging($page, $sum, $total_rows);
        
        return $result;
    }
    
}